﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using RENIT.DragNDropUpload.Utils;
using Microsoft.SharePoint;

namespace RENIT.DragNDropUpload.Handlers
{
    public class UploadHandlerImpl : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                var request = context.Request;
                if (!request.HttpMethod.Equals("POST", StringComparison.InvariantCultureIgnoreCase))
                {
                    throw new InvalidOperationException("This handler supports only post requests");
                }
                if (request.ContentLength == 0)
                {
                    throw new InvalidOperationException("Uploading of empty files, folders, and other zero-length objects does not supported.");
                }
                Guid siteID = new Guid(request.QueryString["siteId"]);
                Guid webID = new Guid(request.QueryString["webId"]);
                Guid listID = new Guid(request.QueryString["listId"]);
                var folderUrl =request.QueryString["folderUrl"];
                var fileName = HttpUtility.UrlDecode(request.QueryString["fileName"] ?? string.Empty);
                var overwrite = false;
                if (!bool.TryParse((request.QueryString["overwrite"] ?? "false").ToLowerInvariant(), out overwrite))
                {  
                    overwrite = false;
                }
                using (var webGuard = WebGuard.OpenWeb(siteID, webID))
                {
                    var docLibAdapter = string.IsNullOrEmpty(folderUrl)  
                        ? webGuard.GetDocumentLibraryByListId(listID) 
                        : webGuard.GetDocumentLibraryByFolder(folderUrl);
                    //TODO: implement "file already Exists reply
                    if (!docLibAdapter.SaveFile(fileName, request.InputStream, overwrite))
                    {
                        docLibAdapter.SaveFile(fileName, request.InputStream, true);
                    }

                }
                
                //request.SaveAs(@"C:\Temp\" + , false);
                SendReply(context, new SimpleJSON().Set("result", "ok").Set("message", "File uploaded successfuly").Set("fileUrl", fileName));
            }
            catch (Exception err)
            {
                SendReply(context, new SimpleJSON().Set("result", "error").Set("message", err.Message).Set("callStack", err.StackTrace.ToString()));
            }
        }

        private void SendReply(HttpContext ctx, SimpleJSON obj)
        {
            ctx.Response.ContentType = "text/json";
            ctx.Response.ContentEncoding = Encoding.UTF8;
            ctx.Response.Write(obj.Serialize());
        }

        #endregion
    }
}
